package mychat.server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;

import mychat.dao.UserDao;
import mychat.util.DaoFactory;
import mychat.util.MessageFactory;
import mychat.vo.Message;
import mychat.vo.User;

public class Server {
	static UserDao userdao = null;
	static ServerSocket ss = null;
	static DataInputStream in = null;
	static DataOutputStream out = null;
	static Socket s = null;
	static ProcessorList processorList = new ProcessorList();

	public static void main(String[] args) {

		try {
			ss = new ServerSocket(6666);
			userdao = DaoFactory.getUserDao();

			while (true) {
				s = ss.accept();
				try {
					System.out.println("A Client Connetion!");
					in = new DataInputStream(s.getInputStream());
					out = new DataOutputStream(s.getOutputStream());
					String message = in.readUTF();
					System.out.println(message);
					Message msg = MessageFactory.getMessage(message);
					process(msg);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				} finally {
					try {
						if (in != null)
							in.close();
					} catch (IOException e) {
					} finally {
						try {
							if (out != null)
								out.close();
						} catch (IOException e) {
						} finally {
							try {
								if (s != null && !s.isClosed())
									s.close();
							} catch (IOException e) {
							}
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (!ss.isClosed())
					ss.close();
			} catch (IOException e) {
			} finally {
				System.out.println("Exit");
			}
		}
	}

	private static void process(Message msg) throws Exception {
		String from = msg.getFrom();
		String to = msg.getTo();
		String content = msg.getContent();
		switch (msg.getType()) {
		case Message.LOGIN:
			login(from, content);
			break;
		}
	}

	private static void login(String name, String password) throws Exception {
		if (null != processorList.getProcessor(name)) {
			out.writeUTF("LOGIN");
			return;
		}
		User user = userdao.findByName(name);
		if (user != null && user.getPassword().equalsIgnoreCase(password)) {
			ClientProcessor client = new ClientProcessor(s, out, in, user);
			processorList.addClient(client);
			s=null;
			in=null;
			out=null;
			client.start();
		} else {
			out.writeUTF("NO");
		}
	}

}
